<?php
/*
 * Try a recipe
 */

F3::call('authentication.php');
if (F3::exists('auth_error'))
{
  // authentication failed
  return;
}
if (!F3::exists('POST.rating')){
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "we need rating to try");
	echo json_encode($err);
	return;
}
$uid = F3::get('SESSION.user_id');
$rid = F3::get('PARAMS["recipe_id"]');
$param = array('1'=>$uid, '2'=>$rid);

$result = DB::sql("SELECT * from ratings where uid = ? AND rid = ?", $param);
if(count($result)>0){
	//we have already tried this recipe, you need to update it only.
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Recipe has already tried");
	echo json_encode($err);
	return;
}

$param = array('1'=>$rid, '2'=>$uid, '3'=>F3::get('POST.rating'));
DB::sql("INSERT INTO ratings(rid, uid, rating) VALUES(?,?,?)",$param);

header('HTTP/1.1 200');
header("Content-Type: application/json");
$response = array('1'=>"Success");
echo json_encode($response);
?>